//
//  ViewController.m
//  TiaoShiXcode
//
//  Created by 曹想 on 2019/3/29.
//  Copyright © 2019 bigger. All rights reserved.
//

#import "ViewController.h"
#define TestURL @"http://ip.taobao.com/service/getIpInfo.php?ip=117.89.35.58"

//#define TestURL @"https://www.jianshu.com/p/b43027f33ad2"
typedef void(^SucessBlock)(void);

@interface ViewController ()

//@property (nonatomic,strong) dispatch_queue_t queue;


@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //这个队列不能使用全局队列和串行队列。栏栅函数是可以做到控制网络请求的
    dispatch_queue_t queue = dispatch_queue_create("queue", DISPATCH_QUEUE_CONCURRENT);
//    //dispatch_barrier_sync(queue, ^{
//    dispatch_async(queue, ^{
//         [self testHttp];
//    });
//    //});
//    dispatch_barrier_sync(queue, ^{
//        [self testHttp2];
//    });
    
    dispatch_semaphore_t signal = dispatch_semaphore_create(1);
    dispatch_async(queue, ^{
      dispatch_semaphore_wait(signal, DISPATCH_TIME_FOREVER);
        [self testHttp:^{
            dispatch_semaphore_signal(signal);
        }];
    });
    
//    dispatch_semaphore_wait(signal, DISPATCH_TIME_FOREVER);
    
    dispatch_async(queue, ^{
        dispatch_semaphore_wait(signal, DISPATCH_TIME_FOREVER);
        [self testHttp2:^{
            dispatch_semaphore_signal(signal);
        }];
    });
    //dispatch_semaphore_wait(signal, DISPATCH_TIME_FOREVER);
}


-(void)testHttp:(SucessBlock)sucessBlock{
    NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:TestURL]];
    
    NSURLSession * session = [NSURLSession sharedSession];
    
    NSURLSessionTask * task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        //NSString * dictString = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
        NSLog(@"%@===",dict);
        sucessBlock();
        //NSLog(@"%@====",[NSThread currentThread]);
    }];
    [task resume];
}

-(void)testHttp2:(SucessBlock)sucessBlock{
    NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:TestURL]];
    
    NSURLSession * session = [NSURLSession sharedSession];
    
    NSURLSessionTask * task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        //NSString * dictString = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
        NSLog(@"%@//////",dict);
        sucessBlock();
        //NSLog(@"%@////",[NSThread currentThread]);
    }];
    [task resume];
}


@end
